package alingrad.engine.src.core;

import java.io.IOException;

/**
 * Thread which runs the game.
 * @author alingrad
 *
 */
public class GameThread extends Thread {
	/**
	 * The main loop of the game.
	 */
	private MainLoop game;

	/**
	 * Whether the game is finished or not.
	 */
	private static boolean isFinished;

	/**
	 * The system time of the last update.
	 */
	private long lastTickMs;

	/**
	 * Whether the game is ready to begin.
	 */
	private boolean ready = true;

	/**
	 * Constructs the game thread.
	 */
	public GameThread() {
		game = new MainLoop();
		new RenderManager();
		isFinished = false;
	}

	/**
	 * Finishes the thread.
	 */
	public static void finish() {
		isFinished = true;
	}

	/**
	 * Loads the game.
	 */
	public void loadGame() {
		try {
			MainLoop.load();
		}catch (IOException ex) {
			System.err.println("Error in loading game.");
			System.exit(1);
		}
	}

	/**
	 * Tells the game its ready to begin.
	 */
	public void ready() {
		ready = true;
	}

	@Override
	public void run() {
		super.run();
		loadGame();
		while (true) {
			if (ready)
				break;
		}
		game.initialize();
		RenderManager.initialize();
		lastTickMs = System.currentTimeMillis();
		// THE HEART BEAT!
		while (!isFinished) {
			long currentTickMs = System.currentTimeMillis();
			long delta = currentTickMs - lastTickMs;
			game.update(delta);
			RenderManager.draw();
			lastTickMs = currentTickMs;
		}
	}
}
